-- 竞技场 众神之战 王者争霸
--
-- 活动时间: 一周内，day2的21.05 - 21:49，day5重复
-- 活动准备：竞技场排名前128名玩家(包含竞技场npc)
-- 活动内容：6轮选拔赛+32强赛的5轮战斗，每轮战斗分别包含3个小阶段（准备（60s）、竞猜(60s)和战斗阶段(120s)）
--

local ObjHuman = require("core.ObjHuman")
local JjcGodWarExcel = require("excel.jjcGodWar")
local JjcGodWarDB = require("jjcGodWar.JjcGodWarDB")
local RoleLogic = require("role.RoleLogic")
local Util = require("common.Util")
local Msg = require("core.Msg")
local Broadcast = require("broadcast.Broadcast")
local Lang = require("common.Lang")
local BagLogic = require("bag.BagLogic")
local ItemDefine = require("bag.ItemDefine")
local JjcDB = require("jjc.JjcDB")
local JjcActLogic = require("jjc.JjcActLogic")
local CombatDefine = require("combat.CombatDefine")
local HeroGrid = require("hero.HeroGrid")
local JjcGodWarCombat = require("jjcGodWar.JjcGodWarCombat")
local MailExcel = require("excel.mail")
local LiLianLogic = require("dailyTask.LiLianLogic")
local MoshouLogic = require("moshou.MoshouLogic")
local MailManager = require("mail.MailManager")
local RoleHeadLogic = require("role.RoleHeadLogic")
local RoleDBLogic = require("role.RoleDBLogic")
local MonsterExcel = require("excel.monster")
local Grid = require("bag.Grid")
local CombatLogic = require("combat.CombatLogic")
local CommonDB = require("common.CommonDB")
local RoleSystemLogic = require("roleSystem.RoleSystemLogic")
local RoleSystemDefine = require("roleSystem.RoleSystemDefine")
local MailDefine = require("mail.MailIdDefine")
local RoleExcel = require("excel.role")
local YunYingLogic = require("yunying.YunYingLogic")
local JjcLogic = require("jjc.JjcLogic")
local FilterUtil = require("common.FilterUtil")
local HeroGrowUp = require("absAct.HeroGrowUp")

GODWAR_STATE_WAIT = 0 		--尚未开启
GODWAR_STATE_XUANBA1 = 1 	--选拔赛1
GODWAR_STATE_XUANBA2 = 2 	--选拔赛2
GODWAR_STATE_XUANBA3 = 3 	--选拔赛3
GODWAR_STATE_XUANBA4 = 4 	--选拔赛4
GODWAR_STATE_XUANBA5 = 5 	--选拔赛5
GODWAR_STATE_XUANBA6 = 6 	--选拔赛6
GODWAR_STATE_PAIWEI32 = 7 	--32强
GODWAR_STATE_PAIWEI16 = 8 	--16强
GODWAR_STATE_PAIWEI8 = 9 	--8强
GODWAR_STATE_PAIWEI4 = 10 	--4强九 零 一 起玩 www.9 01  7 5.com 
GODWAR_STATE_PAIWEI1 = 11 	--决赛
GODWAR_STATE_END = 12 		--活动结束（每周第二期众神之战活动结束后才有活动结束这个状态）

GODWAR_JIEDUAN_ZHUNBEI = 1  --准备阶段
GODWAR_JIEDUAN_JINGCAI = 2  --竞猜阶段
GODWAR_JIEDUAN_COMBAT = 3  	--战斗阶段

GODWAR_START_DAY1 = 2 --竞技场每周擂台赛第二天
GODWAR_START_DAY2 = 5 --竞技场每周擂台赛第五天

GODWAR_START_TIME = 21 * 3600 + 5 * 60 --21.05开始本期活动 759000

GODWAR_JIEDUAN_ZHUNBEI_TIME = 60 --准备阶段60s
GODWAR_JIEDUAN_JINGCAI_TIME = 60 --竞猜阶段60s
GODWAR_JIEDUAN_COMBAT_TIME = 120 --战斗阶段120s
GODWAR_ACT_TIME = 11*(GODWAR_JIEDUAN_ZHUNBEI_TIME + GODWAR_JIEDUAN_JINGCAI_TIME + GODWAR_JIEDUAN_COMBAT_TIME)--一期活动持续时间
GODWAR_PAIWEI_MAX = 32 --选拔赛后的32强人数

local GODWAR_END_JINGCAI = 28100 --活动结束竞猜币转化上限

-- human.db.jjcGodWar = {  
-- 	mobaiList = nil --今天已膜拜列表
-- 	topRank = nil --历史最高等级
-- 	mobaiCnt = nil --今天累计已膜拜次数
--	finishTipTime = nil --活动结算弹窗 finishTipTime = time
--	jingCaiTip = nil --竞猜活动提醒
-- }

function getStartTime()
	local _,_,startTime = JjcDB.getGodSeasonEndTime()
    if not startTime then return end

    local startTime1 = startTime + (GODWAR_START_DAY1 - 1) * 86400 + GODWAR_START_TIME
    local startTime2 = startTime + (GODWAR_START_DAY2 - 1) * 86400 + GODWAR_START_TIME

    return startTime1,startTime2
end

local function getStartEndTime()
	local startTime1,startTime2 = getStartTime()
    if not startTime1 then return end

    local godWarStartTime,godWarEndTime
    local nowTime = os.time()
    if nowTime < startTime1 + GODWAR_ACT_TIME then
    	 godWarStartTime = startTime1
    elseif nowTime >= startTime1 + GODWAR_ACT_TIME and nowTime < startTime2 + GODWAR_ACT_TIME then
    	godWarStartTime = startTime2 	
    end
    if not godWarStartTime then return end

    godWarEndTime = godWarStartTime + GODWAR_ACT_TIME

	return godWarStartTime,godWarEndTime
end

--获取当前时间的状态
--活动开启前后，仅返回状态和下一期活动开始的倒计时
--若是本周的第二期活动则返回结束状态和倒计时0
--活动期间，返回本期活动正在进行的比赛，什么阶段，倒计时
function getNowGodWarState()
	local godWarStartTime,godWarEndTime = getStartEndTime()
	if not godWarEndTime or not godWarStartTime then
		return GODWAR_STATE_END, 0, 0
	end

	local now = os.time()
	if now < godWarStartTime then
		return GODWAR_STATE_WAIT, 0, godWarStartTime - now
	end

	for round=GODWAR_STATE_XUANBA1,GODWAR_STATE_PAIWEI1 do
		local nowStartTime = godWarStartTime + (round - 1) * (GODWAR_JIEDUAN_COMBAT_TIME + GODWAR_JIEDUAN_JINGCAI_TIME + GODWAR_JIEDUAN_ZHUNBEI_TIME)
		local nowEndTime = nowStartTime + GODWAR_JIEDUAN_COMBAT_TIME + GODWAR_JIEDUAN_JINGCAI_TIME + GODWAR_JIEDUAN_ZHUNBEI_TIME
		if now >= nowStartTime and now < nowEndTime then
			local middleTime = now - nowStartTime
			local state = GODWAR_JIEDUAN_ZHUNBEI
			local leftTime = nowStartTime + GODWAR_JIEDUAN_ZHUNBEI_TIME - now
			if middleTime >= GODWAR_JIEDUAN_ZHUNBEI_TIME and middleTime < GODWAR_JIEDUAN_ZHUNBEI_TIME + GODWAR_JIEDUAN_JINGCAI_TIME then
				state = GODWAR_JIEDUAN_JINGCAI
				leftTime = nowStartTime + GODWAR_JIEDUAN_ZHUNBEI_TIME + GODWAR_JIEDUAN_JINGCAI_TIME - now
			elseif middleTime >= GODWAR_JIEDUAN_ZHUNBEI_TIME + GODWAR_JIEDUAN_JINGCAI_TIME then
				state = GODWAR_JIEDUAN_COMBAT
				leftTime = nowStartTime + GODWAR_JIEDUAN_COMBAT_TIME + GODWAR_JIEDUAN_JINGCAI_TIME + GODWAR_JIEDUAN_ZHUNBEI_TIME - now
			end
			return round, state, leftTime
		end
	end
end

local function getSaiJiTime()
	local godWarStartTime,godWarEndTime = getStartEndTime()
	if not godWarEndTime or not godWarStartTime then
		return 0, 0
	end

	local now = os.time()
	local day = Util.getWeekDay(now) - 1

	if now < godWarStartTime then
		return godWarStartTime, godWarStartTime - now
	elseif now >= godWarStartTime and now < godWarEndTime then
		return godWarStartTime, godWarEndTime - now
	end
end

local function makeGodWarTopThree(net, human)
	local state,round,leftTime = getNowGodWarState()
	net[0] = 3
	local conf = JjcGodWarExcel.chenghaoReward
	local rank2Uuid = JjcGodWarDB.getGodWarRank2Uuid()
	local uuid2Roles = JjcGodWarDB.getGodWarUuid2Roles()
	local lastTopThreeData = JjcGodWarDB.getGodWarLastTopThree()
	for rank=1,3 do
		net[rank].name = ""
		net[rank].uuid = ""
		net[rank].rank = rank
		net[rank].beiMoBai = 0
		net[rank].kingBody = 304002
		net[rank].chenghaoID = conf[rank].chenghaoID
		net[rank].chenghaoName = ""
        if conf[rank].chenghaoID and RoleExcel.chenghao[conf[rank].chenghaoID] then
            net[rank].chenghaoName = RoleExcel.chenghao[conf[rank].chenghaoID].name 
        end
		net[rank].isMoBai  = 0
		local roleData = nil
		if state == GODWAR_STATE_WAIT or state == GODWAR_STATE_END then
			if rank2Uuid and uuid2Roles then
				local uuid = rank2Uuid[rank]
				roleData = uuid2Roles[uuid]
			end
		else
			if lastTopThreeData then
				roleData = lastTopThreeData[rank]
			end
		end

		if roleData then
			local rolebase = roleData.rolebase
			if JjcDB.isNpc(roleData) then				
				rolebase = roleData
				local data = JjcDB.getJjcData(rolebase.uuid)
				net[rank].beiMoBai = data.worshipCnt or 0
				if data._id ~= human.db._id and (human.db.jjcWorship == nil or human.db.jjcWorship[data._id] == nil) then
					net[rank].isMoBai = 1
				end	
					
				net[rank].kingBody = rolebase.body or 304002
			else
				local db = RoleDBLogic.getDb(roleData.uuid)
				if db ~= nil then
					net[rank].beiMoBai = db.jjcBeWorship or 0
					if db._id ~= human.db._id and (human.db.jjcWorship == nil or human.db.jjcWorship[db._id] == nil) then
						net[rank].isMoBai = 1
					end
					net[rank].kingBody = db and db.body or 304002
				end
			end
			net[rank].name = rolebase.name or ""
			net[rank].uuid = roleData.uuid			
		end
	end
end

local function getMyTopRank(human)
	local myGodWar = human.db.jjcGodWar
	return myGodWar and myGodWar.topRank or 0
end


local function makeGodWarRank(net,human,rank,uuid,roleData)
	net.rank = rank
	local rolebase = roleData.rolebase
	local isNpc = false
	if JjcDB.isNpc(roleData) then
		isNpc = true
		rolebase = roleData
	end
	RoleLogic.makeRoleBase(rolebase,net.roleBase)
	net.beiMoBai = 0
	net.isMoBai = 0
	net.jifen = roleData.point or 0

	if isNpc then
		local data = JjcDB.getJjcData(rolebase.uuid)
		net.beiMoBai = data.worshipCnt or 0
		if uuid then			
			if data._id ~= human.db._id and (human.db.jjcWorship == nil or human.db.jjcWorship[data._id] == nil) then
                net.isMoBai = 1
            end
		end
	else
		local db = RoleDBLogic.getDb(roleData.uuid)
		if db ~= nil then
			net.beiMoBai = db.jjcBeWorship or 0
			if db._id ~= human.db._id and (human.db.jjcWorship == nil or human.db.jjcWorship[db._id] == nil) then
                net.isMoBai = 1
            end
		else
			local data = JjcDB.getJjcData(rolebase.uuid)
			net.beiMoBai = data.worshipCnt or 0
			if uuid then			
				if data._id ~= human.db._id and (human.db.jjcWorship == nil or human.db.jjcWorship[data._id] == nil) then
					net.isMoBai = 1
				end
			end		
		end
	end
end

function CG_JJCGODWAR_QUERY(human)
	if not RoleSystemLogic.isOpen(human, RoleSystemDefine.ROLE_SYS_ID_1302, true) then
		return
	end
	local msgRet = Msg.gc.GC_JJCGODWAR_QUERY

	local myGodWarData = JjcGodWarDB.getGodWarDataByUuid(human.db._id)
	local myRank = JjcGodWarDB.getRankByUuid(human.db._id)
	msgRet.myBeiMoBai = myGodWarData and myGodWarData.beiMoBai or 0
	
	makeGodWarTopThree(msgRet.topThree, human)
	msgRet.myTopRank = getMyTopRank(human)
	msgRet.myRank = myRank or 0

	local now = os.time()
	local state,round,leftTime = getNowGodWarState()
	local startTime1,startTime2 = getStartTime()
    if startTime1 and startTime2 then 
		-- 如果 第一阶段的 赛季结束  第二阶段未开始 强制 把 State 设置为 赛季结束 给予前端 默认显示 4强
		if now > startTime1 + GODWAR_ACT_TIME and now < startTime2 - 15 then
			state = GODWAR_STATE_END
			round =  0
		end
	end
	msgRet.state = state
	msgRet.jieDuan = round
	local startTime,leftTime = getSaiJiTime()
	msgRet.nextStartTime = startTime
	msgRet.leftTime = leftTime	
	--Msg.trace(msgRet)
	Msg.send(msgRet,human.fd)

	local godWarDB = JjcGodWarDB.getGodWarDB()
	if myGodWarData and not myGodWarData.sendFinalTip and godWarDB.isSendReward then
		local msgRet = Msg.gc.GC_JJCGODWAR_RANK_TIP
		
		local allMatch = JjcGodWarDB.getAllMatchByUuid(human.db._id)
		if not allMatch then return end

		msgRet.myRank = myRank
		msgRet.totalFight = #allMatch
		
		local winCnt = 0
		for i=1,#allMatch do
			if allMatch[i].winUuid == human.db._id then
				winCnt = winCnt + 1
			end
		end
		
		msgRet.winCnt = winCnt
		Msg.send(msgRet,human.fd)
		myGodWarData.sendFinalTip = true
		JjcGodWarDB.updateGodWarRoleDataByUuid(myGodWarData,human.db._id)
	end
end

-- 排行榜
function CG_JJCGODWAR_BOARD_QUERY(human)
	ObjHuman.updateDaily(human)
	local msgRet = Msg.gc.GC_JJCGODWAR_BOARD_QUERY

	local rank2Uuid = JjcGodWarDB.getGodWarRank2Uuid()
	msgRet.rankList[0] = 0
	if rank2Uuid then
		msgRet.rankList[0] = 50
		for rank=1,50 do
			local uuid = rank2Uuid[rank]
			local roleData = JjcGodWarDB.getGodWarDataByUuid(uuid)
			makeGodWarRank(msgRet.rankList[rank],human,rank,uuid,roleData)
		end
	end

	local myGodWarData = JjcGodWarDB.getGodWarDataByUuid(human.db._id)
	local myRank = JjcGodWarDB.getRankByUuid(human.db._id)
	if not myGodWarData then
		local net = msgRet.myRank
		net.rank = 0
		net.isMoBai = 0
		net.jifen = 0
		net.beiMoBai = 0
		RoleLogic.makeRoleBase(human.db,net.roleBase)
	else
		makeGodWarRank(msgRet.myRank,human,myRank,_,myGodWarData)
	end
	--Msg.trace(msgRet)
	Msg.send(msgRet,human.fd)
end

-- 膜拜
function CG_JJCGODWAR_MOBAI(human,uuid)
	-- 不能膜拜自己
    if uuid == human.db._id then
        return
    end

    -- 初始化膜拜数据
    human.db.jjcWorship = human.db.jjcWorship or {}
    human.db.jjcWorship.count = human.db.jjcWorship.count or 0


    -- 每日膜拜已达上限
    if human.db.jjcWorship.count >= JjcLogic.JJC_WORSHIP_CNT then
        return  Broadcast.sendErr(human, Lang.GODWAR_MOBAI_ERR) 
    end

    -- 已膜拜过此玩家
    if human.db.jjcWorship[uuid] ~= nil then
        return Broadcast.sendErr(human, Lang.GODWAR_MOBAI_HAD) 
    end

    -- 写数据库
    human.db.jjcWorship[uuid] = 1
    human.db.jjcWorship.count = human.db.jjcWorship.count + 1

    -- 写被膜拜玩家数据库
    local worshipCnt = 0
    local db = RoleDBLogic.getDb(uuid)
    if db == nil then
        JjcDB.updateWorshipCnt(uuid)
        worshipCnt = JjcDB.getWorshipCnt(uuid)
    else
        db.jjcBeWorship = db.jjcBeWorship or 0
        db.jjcBeWorship = db.jjcBeWorship + 1
        RoleDBLogic.saveRole(db) 
        worshipCnt = db.jjcBeWorship
    end

	local config = JjcGodWarExcel.mobai[1]

	local reward = config.mobaiReward
	-- 给奖励
	BagLogic.addItem(human, reward[1], reward[2], "jjc_worship")
	Broadcast.sendErr(human, Util.format(Lang.JJC_WORSHIP_GOOD, reward[2]))

    local msgRet = Msg.gc.GC_JJCGODWAR_MOBAI
	msgRet.uuid = uuid
	msgRet.beiMoBai = worshipCnt
    Msg.send(msgRet,human.fd)

	--Broadcast.sendErr(human, Lang.GODWAR_MOBAI_REWARD)
end

local function makeGodWarNowState(net)
	local state,round,leftTime = getNowGodWarState()
	net.state = state
	net.jieDuan = round
	net.leftTime = leftTime
end

local function makeNpcInfo(net,roleData)
	local monsterOutID = roleData.monsterOutID
    local monsterOutConfig = MonsterExcel.monsterOut[monsterOutID]

    local fakeHuman = {}
    fakeHuman.db = roleData
    RoleLogic.getRoleBase(fakeHuman, net.roleBase)

    net.heroList[0] = CombatDefine.COMBAT_HERO_CNT
	net.formation = monsterOutConfig.formation
		
	local monsterObjList = CombatLogic.getMonsterObjList(monsterOutID)
	for i = 1, CombatDefine.COMBAT_HERO_CNT do
        local obj = monsterObjList[i]
        local monsterID = obj and obj.id or 0
        local index = obj and obj.bagIndex or 0

        HeroGrid.makeHeroSimpleByMonsterID(net.heroList[i], monsterID,{lv = obj and obj.lv or 0})
		net.heroList[i].index = index
    end

	net.helpList[0] = 0
end

local function makeGodWarTeam(net,roleData, side)
	if JjcDB.isNpc(roleData) then
		makeNpcInfo(net,roleData)
		return
	end
	local state,round,leftTime = getNowGodWarState()
	local objList, helpList, rolebase, formation
	if round == GODWAR_JIEDUAN_ZHUNBEI or round == GODWAR_JIEDUAN_JINGCAI then
		local fakeHuman = ObjHuman.onlineUuid[roleData.uuid]
		if fakeHuman then
			objList, helpList, rolebase, formation = CombatLogic.getHumanObjList(fakeHuman, CombatDefine.COMBAT_TYPE4)
		end	
	end

	if not objList then
		objList = roleData.objList
		helpList = roleData.helpList
		rolebase = roleData.rolebase
		formation = roleData.formation
	end

	net.formation = formation
	RoleLogic.makeRoleBase(rolebase,net.roleBase,CombatDefine.COMBAT_TYPE4)
    net.heroList[0] = CombatDefine.COMBAT_HERO_CNT
    for i=1,CombatDefine.COMBAT_HERO_CNT do
		local grid = objList and objList[i]
    	local bagIndex = grid and grid.bagIndex or 0
    	HeroGrid.makeHeroSimple(net.heroList[i], grid, bagIndex)
    end

    net.helpList[0] = 0
	if helpList and helpList[1] then
		local helpPos = CombatDefine.getHelpPos(side,CombatDefine.HELP_TYPE1)
		for _, help in pairs(helpList) do
			help.pos = helpPos
			if CombatLogic.fontCombatHelpNet(net.helpList[net.helpList[0] + 1], help, helpPos) then
				net.helpList[0] = net.helpList[0] + 1
			end
		end	
	end
	
--[[
if helpList and helpList[1] then
		len = len + 1
		local helpPos = CombatDefine.getHelpPos(side,CombatDefine.HELP_TYPE1)
		MoshouLogic.setCombatHelp(net.helpList[len],helpList[1],helpPos)
	end
	net.helpList[0] = len
]]
	
end

local function makeGodWarTeamHistory(net,combatInfo,side)
	--require("common.Util").printTable(combatInfo)
	local rolebase = combatInfo.attacker
	local formation = combatInfo.atkFormation or 1
	if side == CombatDefine.DEFEND_SIDE then
		rolebase = combatInfo.defender
		formation = combatInfo.defFormation or 1
	end

	local objList = combatInfo.objList
	local helpList = combatInfo.helpList

	net.formation = formation
	RoleLogic.makeRoleBase(rolebase,net.roleBase)

	net.heroList[0] = 0
	for _,pos in ipairs(CombatDefine.SIDE2POS[side]) do
		local grid = objList and objList[pos]
		net.heroList[0] = net.heroList[0] + 1
		local index = net.heroList[0]
		local bagIndex = grid and grid.bagIndex or 0
		HeroGrid.makeHeroSimple(net.heroList[index], grid, bagIndex)			
	end

	net.helpList[0] = 0
	if helpList and helpList[1] then
		local helpPos = CombatDefine.getHelpPos(side,CombatDefine.HELP_TYPE1)
		for _, help in pairs(helpList) do
			help.pos = helpPos
			if CombatLogic.fontCombatHelpNet(net.helpList[net.helpList[0] + 1], help, helpPos) then
				net.helpList[0] = net.helpList[0] + 1
			end
		end	
	end

	--[[
local len = 0
	if helpList and helpList[1] and helpList[1] > 0 then
		len = len + 1
		MoshouLogic.setHelp(net.helpList[len],helpList[1])
	end
	net.helpList[0] = len

	]]
	
end

-- 我的比赛界面
-- 活动开启倒计时，显示距开始xxxx
-- 活动结束显示，有参与过战斗的显示最后一场战斗，没有资格的显示没资格
-- 活动中，128名以外的显示没资格
function CG_JJCGODWAR_MYMATCH(human)
	local msgRet = Msg.gc.GC_JJCGODWAR_MYMATCH
	msgRet.teams[0] = 0
	makeGodWarNowState(msgRet.state)
	msgRet.vestID = ""
	msgRet.history = 0
	msgRet.isWin = 0
	local state,round,leftTime = getNowGodWarState()
	--print("state,leftTime",state,leftTime)
	if state == GODWAR_STATE_WAIT then --尚未开启
	--	Msg.trace(msgRet)
		Msg.send(msgRet,human.fd)
		return
	end
	
	local pairsData,nowCombat,getMatch2FightState = JjcGodWarDB.getGodWarPairsDataByUuid(human.db._id)
	if pairsData then
		local atkUuid = pairsData.atkUuid
		local defUuid = pairsData.defUuid
		local winUuid = pairsData.winUuid
		msgRet.teams[0] = 2
		if nowCombat then
			local atkRoleData = JjcGodWarDB.getGodWarDataByUuid(atkUuid)
			local defRoleData = JjcGodWarDB.getGodWarDataByUuid(defUuid)
			makeGodWarTeam(msgRet.teams[1],atkRoleData,CombatDefine.ATTACK_SIDE)
			makeGodWarTeam(msgRet.teams[2],defRoleData,CombatDefine.DEFEND_SIDE)
			if round == GODWAR_JIEDUAN_COMBAT then
				msgRet.vestID = pairsData.vestID or ""  
			end
		else
			local record = JjcGodWarDB.getRecord(pairsData.vestID)
			if not record then return end
			local combatInfo = record.combatInfo
			makeGodWarTeamHistory(msgRet.teams[1],combatInfo,CombatDefine.ATTACK_SIDE)
			makeGodWarTeamHistory(msgRet.teams[2],combatInfo,CombatDefine.DEFEND_SIDE)
			msgRet.history = getMatch2FightState
			msgRet.vestID = pairsData.vestID or ""
			if winUuid and winUuid == atkUuid then
				msgRet.isWin = 1
			end
		end
	end
	--Util.printTable(msgRet)
--	Msg.trace(msgRet)
	Msg.send(msgRet,human.fd)
end

--竞猜界面
function CG_JJCGODWAR_JINGCAI(human)
	if not RoleSystemLogic.isOpen(human, RoleSystemDefine.ROLE_SYS_ID_1302, true) then
		return
	end

	local msgRet = Msg.gc.GC_JJCGODWAR_JINGCAI
	local state,round,leftTime = getNowGodWarState()
	local jingCaiPairs = nil
	local needState = nil
	local jingcaiBi = 0
	if state == GODWAR_STATE_END or state == GODWAR_STATE_WAIT then
		jingCaiPairs = JjcGodWarDB.getGodWarJingCaiPairs(GODWAR_STATE_PAIWEI1)
		needState = GODWAR_STATE_PAIWEI1
	else
		jingCaiPairs = JjcGodWarDB.getGodWarJingCaiPairs(state)
		needState = state
		jingcaiBi = JjcGodWarDB.getJingCaiBiCnt(human,state)
	end

	if not jingCaiPairs and state < GODWAR_STATE_END and  state > GODWAR_STATE_WAIT then
		--生成竞猜队伍  客户端自动切换的时候  服务端还未生成竞猜队伍处理
		JjcGodWarDB.godWarJingCaiPairs()
		jingCaiPairs = JjcGodWarDB.getGodWarJingCaiPairs(state)
		needState = state
		jingcaiBi = JjcGodWarDB.getJingCaiBiCnt(human,state)
	end
	local jingCaiExcel = JjcGodWarExcel.jingCai[1]
	local maxYa = jingCaiExcel.jingCaiYaOneMax
	msgRet.maxYa = maxYa
	msgRet.jingcaiBi = 0
	msgRet.yaUuid = ""
	msgRet.vestID = ""
	msgRet.jingcaiTeam[0] = 0
	msgRet.isWin = 0
	makeGodWarNowState(msgRet.state)

	if jingCaiPairs then
		local atkUuid = jingCaiPairs.atkUuid
		local defUuid = jingCaiPairs.defUuid
		local vestID = jingCaiPairs.vestID or ""
		local winUuid = jingCaiPairs.winUuid	
		msgRet.jingcaiTeam[0] = 2
		if needState == state then
			local atkRoleData = JjcGodWarDB.getGodWarDataByUuid(atkUuid)
			local defRoleData = JjcGodWarDB.getGodWarDataByUuid(defUuid)
			makeGodWarTeam(msgRet.jingcaiTeam[1].team,atkRoleData,CombatDefine.ATTACK_SIDE)
			makeGodWarTeam(msgRet.jingcaiTeam[2].team,defRoleData,CombatDefine.DEFEND_SIDE)
			if round ~= GODWAR_JIEDUAN_COMBAT then
				vestID = ""
			end
		else
			local record = JjcGodWarDB.getRecord(vestID)
			if not record then return end

			local combatInfo = record.combatInfo
			makeGodWarTeamHistory(msgRet.jingcaiTeam[1].team,combatInfo,CombatDefine.ATTACK_SIDE)
			makeGodWarTeamHistory(msgRet.jingcaiTeam[2].team,combatInfo,CombatDefine.DEFEND_SIDE)
		end

		local atkPei,defPei = JjcGodWarDB.getJingcaiPei(needState)
		msgRet.jingcaiTeam[1].pei = atkPei * 100
		msgRet.jingcaiTeam[2].pei = defPei * 100

		msgRet.jingcaiBi = jingcaiBi
		msgRet.vestID = vestID
		local yaData = JjcGodWarDB.getJingCaiYaZhu(human.db._id)
		msgRet.yaUuid = yaData and yaData[needState] and yaData[needState].yaUuid or ""

		if winUuid and atkUuid == atkUuid then
			msgRet.isWin = 1
		end
	end
	--Msg.trace(msgRet)
	Msg.send(msgRet,human.fd)
end

--竞猜提醒
function GC_JJCGODWAR_JINGCAI_TIP(human)
	local msgRet = Msg.gc.GC_JJCGODWAR_JINGCAI_TIP
	local jingCaiExcel = JjcGodWarExcel.jingCai[1]
	msgRet.items[0] = #jingCaiExcel.jingCaiShowReward
	for i=1,#jingCaiExcel.jingCaiShowReward do
		local itemID = jingCaiExcel.jingCaiShowReward[i][1]
		local itemCnt = jingCaiExcel.jingCaiShowReward[i][2]
		Grid.makeItem(msgRet.items[i],itemID,itemCnt)
	end

	--Msg.trace(msgRet)
	Msg.send(msgRet,human.fd)
end

--竞猜信息刷新
function CG_JJCGODWAR_JINGCAI_CHECK(human)
	local state,round,leftTime = getNowGodWarState()
	if state == GODWAR_STATE_WAIT or state == GODWAR_STATE_END then return end
	if round ~= GODWAR_JIEDUAN_JINGCAI then
		return
	end
	local msgRet = Msg.gc.GC_JJCGODWAR_JINGCAI_CHECK
	local atkPei,defPei = JjcGodWarDB.getJingcaiPei(state)
	msgRet.peiLeft = atkPei * 100
	msgRet.peiRight = defPei * 100
	Msg.send(msgRet,human.fd)
end

--押注
function CG_JJCGODWAR_JINGCAI_YA(human,targetUuid,yaZhuCnt)
	if yaZhuCnt <= 0 then return end

	local state,round,leftTime = getNowGodWarState()
	if round ~= GODWAR_JIEDUAN_JINGCAI 
		or leftTime <= 0 then
		return Broadcast.sendErr(human,Lang.GODWAR_JINGCAI_ERR)
	end

	local yaData = JjcGodWarDB.getYaZhuDataByUuid(human.db._id)
	if not yaData then return end

	if yaData.jingCai and yaData.jingCai[state] then
		Broadcast.sendErr(human,Lang.GODWAR_JINGCAI_HAD)
		return
	end

	local jingCaiPairs = JjcGodWarDB.getGodWarJingCaiPairs(state)
	local atkUuid = jingCaiPairs.atkUuid
	local defUuid = jingCaiPairs.defUuid

	if targetUuid ~= atkUuid 
		and targetUuid ~= defUuid then
		return
	end

	local jingCaiExcel = JjcGodWarExcel.jingCai[1]
	local maxYa = jingCaiExcel.jingCaiYaOneMax
	if yaZhuCnt > maxYa then 
		Broadcast.sendErr(human,Lang.GODWAR_JINGCAI_OK) 
		return 
	end

	local now = JjcGodWarDB.getJingCaiBiCnt(human,state)
	if now < yaZhuCnt then return end

	yaData.jingCaiBi = now - yaZhuCnt
	JjcGodWarDB.updateGodWarYaZhuByUuid(yaData,human.db._id)
	JjcGodWarDB.updateYaZhuByUuid(human.db._id,targetUuid,yaZhuCnt)

	JjcGodWarDB.jingCaiYaUpdate(targetUuid)
	
	Broadcast.sendErr(human,Lang.GODWAR_JINGCAI_OK) 
	CG_JJCGODWAR_JINGCAI(human)
end

local function calYaWinCnt(yaZhuCnt,yaUuid,winUuid)
	local jingCaiExcel = JjcGodWarExcel.jingCai[1]
	local gap = jingCaiExcel.jingCaiRealPei
	if yaUuid == winUuid then
		return math.floor(yaZhuCnt * gap)
	else
		return 0
	end
end

--我的竞猜查询（新一期活动开始清掉）
function CG_JJCGODWAR_JINGCAI_MY(human)
	local warState,warRound,leftTime = getNowGodWarState()
	local msgRet = Msg.gc.GC_JJCGODWAR_JINGCAI_MY

	msgRet.jingcaiRecord[0] = 0
	local yaData = JjcGodWarDB.getJingCaiYaZhu(human.db._id)
	if yaData then
		for round,data in pairs(yaData) do
			local jingCaiData = JjcGodWarDB.getGodWarJingCaiPairs(round)
			if jingCaiData then
				msgRet.jingcaiRecord[0] = msgRet.jingcaiRecord[0] + 1
				local index = msgRet.jingcaiRecord[0]

				local winUuid = jingCaiData.winUuid or ""
				local atkUuid = jingCaiData.atkUuid
				local defUuid = jingCaiData.defUuid      
				if warState > GODWAR_STATE_WAIT and warState <= round then
					winUuid = ""
				end
				local yaUuid = data.yaUuid
				local yaZhuCnt = data.yaZhuCnt
				
				local atkRoleData = JjcGodWarDB.getGodWarDataByUuid(atkUuid)
				local defRoleData = JjcGodWarDB.getGodWarDataByUuid(defUuid)

				msgRet.jingcaiRecord[index].roleBase[0] = 2
				local atkRolebase = atkRoleData.rolebase
				local defRolebase = defRoleData.rolebase
				if JjcDB.isNpc(atkRoleData) then
					atkRolebase = atkRoleData
				end
				if JjcDB.isNpc(defRoleData) then
					defRolebase = defRoleData
				end
				RoleLogic.makeRoleBase(atkRolebase,msgRet.jingcaiRecord[index].roleBase[1])
				RoleLogic.makeRoleBase(defRolebase,msgRet.jingcaiRecord[index].roleBase[2])
				msgRet.jingcaiRecord[index].winUuid = winUuid
				msgRet.jingcaiRecord[index].round = round
				
				local state = 1
				if winUuid ~= "" then
					state = 0
				end
				msgRet.jingcaiRecord[index].state = state

				msgRet.jingcaiRecord[index].yaCnt = yaZhuCnt
				
				local yaWinCnt = calYaWinCnt(yaZhuCnt,yaUuid,winUuid)
				msgRet.jingcaiRecord[index].yaWinCnt = yaWinCnt

				local yaLosCnt = 0
				if winUuid ~= "" and yaWinCnt == 0 then
					yaLosCnt = yaZhuCnt
				end

				msgRet.jingcaiRecord[index].yaLosCnt = yaLosCnt
				msgRet.jingcaiRecord[index].yaUuid = yaUuid
				msgRet.jingcaiRecord[index].vestID = jingCaiData.vestID or ""
		--		Util.printTable(jingCaiData)
		--		print("  jingCaiData.winUuid   ", jingCaiData.winUuid ,msgRet.jingcaiRecord[index].vestID , msgRet.jingcaiRecord[index].state )
		--		print("   yaLosCnt   ", yaLosCnt, yaWinCnt, msgRet.jingcaiRecord[index].winUuid , warState ,round  )
			end
		end
	end 
--	Msg.trace(msgRet) 
	Msg.send(msgRet,human.fd)
end

--竞猜成功回调
function GC_JJCGODWAR_JINGCAI_WIN(state,godWarDB)
	if state < GODWAR_STATE_WAIT then return end
	local yaZhuDB = godWarDB.uuid2Yazhu
	local jingCaiCalcState = godWarDB.jingCaiCalcState or 0
	if state == jingCaiCalcState then return end
	if not yaZhuDB then return end

	local jingCaiItem = JjcGodWarExcel.jingCai[1].jingCaiItem
	local up = nil
	godWarDB.jingCaiCalcState = state

	local conf = JjcGodWarExcel.jingCai[1]
	for uuid,data in pairs(yaZhuDB) do
		if data.jingCai then
			local jingCai = data.jingCai[state]
			if jingCai then
				local jingCaiData = JjcGodWarDB.getGodWarJingCaiPairs(state)
				local winUuid = jingCaiData.winUuid
				local yaUuid = jingCai.yaUuid
				if yaUuid and winUuid then
					if yaUuid == winUuid then
						local winCnt = calYaWinCnt(jingCai.yaZhuCnt,jingCai.yaUuid,winUuid)
						up = true
						yaZhuDB[uuid].jingCaiBi = yaZhuDB[uuid].jingCaiBi + winCnt
						local sendHuman = ObjHuman.onlineUuid[uuid]
						if sendHuman then
							local msgRet = Msg.gc.GC_JJCGODWAR_JINGCAI_WIN
							msgRet.round = state
							Grid.makeItem(msgRet.items,jingCaiItem,winCnt)
							msgRet.jingcaiBi = yaZhuDB[uuid].jingCaiBi
					--		Msg.trace(msgRet)
							Msg.send(msgRet,sendHuman.fd)
						end
					end
					yaZhuDB[uuid].jingCaiBi = yaZhuDB[uuid].jingCaiBi + conf.jingCaiSongBi
				end
			end
		end
	end

	if state ~= GODWAR_STATE_PAIWEI1 and up then
		JjcGodWarDB.updateGodWarDB(godWarDB)
	end
end


--奖励展示
local function makeGodWarRankReward(net,data)
	net.minRank = data.rankMin
	net.maxRank = data.rankMax
	
	net.rewards[0] = #data.reward
	for i=1,#data.reward do
		Grid.makeItem(net.rewards[i],data.reward[i][1],data.reward[i][2])
	end
end

function CG_JJCGODWAR_RANK_REWARD(human)
	local msgRet = Msg.gc.GC_JJCGODWAR_RANK_REWARD
	local config = JjcGodWarExcel.godWarBoard
	msgRet.godWarReward[0] = #config
	
	for index,data in ipairs(config) do
		makeGodWarRankReward(msgRet.godWarReward[index],data)
	end
 
--	Msg.trace(msgRet) 
	Msg.send(msgRet,human.fd)
end

--32强界面
function CG_JJCGODWAR_PAIWEI_QUERY(human,checkState,fenzuID)
	local msgRet = Msg.gc.GC_JJCGODWAR_PAIWEI_QUERY
	makeGodWarNowState(msgRet.state)
	local godState,round,leftTime = getNowGodWarState()
	if checkState == GODWAR_STATE_PAIWEI32 and godState > GODWAR_STATE_PAIWEI32 then
		checkState = godState
		checkState = checkState > GODWAR_STATE_PAIWEI8 and GODWAR_STATE_PAIWEI8 or godState
	elseif checkState == GODWAR_STATE_PAIWEI4 and godState > GODWAR_STATE_PAIWEI4 then
		checkState = GODWAR_STATE_PAIWEI1
	elseif checkState == GODWAR_STATE_PAIWEI32 and godState == GODWAR_STATE_WAIT then -- 赛季未开启则查询上赛季的战绩
		checkState = GODWAR_STATE_PAIWEI8
	elseif checkState == GODWAR_STATE_PAIWEI4 and godState == GODWAR_STATE_WAIT then
		checkState = GODWAR_STATE_PAIWEI1
	end
	msgRet.group[0] = 0
	local group = JjcGodWarDB.getNowPaiWeiFenzu(checkState,fenzuID)
	--require("common.Util").printTable(group)
	if group then
	--	local jingcaiState,round,leftTime = getNowGodWarState()
		local jingcaiState = checkState
		round = GODWAR_JIEDUAN_JINGCAI_TIME 
		local jingCaiData = JjcGodWarDB.getGodWarJingCaiData(jingcaiState)

		for state,data in pairs(group) do
			msgRet.group[0] = msgRet.group[0] + 1
			local index = msgRet.group[0]
			msgRet.group[index].checkState = state
			msgRet.group[index].fenzuID = fenzuID
			
			msgRet.group[index].roles[0] = #data
			for i=1,#data do
				local rolesNet = msgRet.group[index].roles[i]
				rolesNet.index = i
				rolesNet.roleBase[0] = 2
				local atkUuid = data[i].atkUuid
				local defUuid = data[i].defUuid
				local atkRoleData = JjcGodWarDB.getGodWarDataByUuid(atkUuid)
				local defRoleData = JjcGodWarDB.getGodWarDataByUuid(defUuid)
				local atkRolebase = atkRoleData.rolebase
				local defRolebase = defRoleData.rolebase
				if JjcDB.isNpc(atkRoleData) then
					atkRolebase = atkRoleData
				end
				if JjcDB.isNpc(defRoleData) then
					defRolebase = defRoleData
				end
				RoleLogic.makeRoleBase(atkRolebase,rolesNet.roleBase[1])
				RoleLogic.makeRoleBase(defRolebase,rolesNet.roleBase[2])

				rolesNet.vestID = data[i].vestID or ""
				rolesNet.winUuid = ""
				-- 32强赛中  比赛到下一回合 再显示出胜者给客户端
				if godState == GODWAR_STATE_WAIT or godState > state then					
					rolesNet.winUuid = data[i].winUuid or ""
				end				
			end
			
			local jingcaiIndex = 0
			if jingCaiData and round == GODWAR_JIEDUAN_JINGCAI_TIME 
				and jingcaiState == state
				and jingCaiData.fenzuID == fenzuID then
				local jingCaiPairsIndex = jingCaiData.pairsIndex
				jingcaiIndex = jingCaiPairsIndex
			end

			msgRet.group[index].jingcaiIndex = jingcaiIndex 
		end
	end
	--Msg.trace(msgRet)
	Msg.send(msgRet,human.fd)
end

--获取竞猜猜对次数
function getYaCorrectCnt(yazhuData)
	if not yazhuData or not yazhuData.jingCai then return 0 end

	local correctCnt = 0
	for state,data in pairs(yazhuData.jingCai) do
		local yaUuid = data.yaUuid
		local jingCaiData = JjcGodWarDB.getGodWarJingCaiPairs(state)
		if jingCaiData then
			local winUuid = jingCaiData.winUuid or ""
			if yaUuid == winUuid then
				correctCnt = correctCnt + 1
			end
		end
	end

	return correctCnt
end

local function makeTopRank(human,rank,isSave)
	human.db.jjcGodWar = human.db.jjcGodWar or {}
	if not human.db.jjcGodWar.topRank then
		human.db.jjcGodWar.topRank = rank
	else
		if human.db.jjcGodWar.topRank > rank then
			human.db.jjcGodWar.topRank = rank
		end
	end

	if isSave then
		ObjHuman.save(human)
	end
end

--发送排名奖励 竞技积分奖励
function sendFinalReward(godWarDB)
	local mailConfig = MailExcel.mail[MailDefine.MAIL_ID_ZSZZ_SEASON]
    local title = mailConfig.title
    local senderName = mailConfig.senderName
	for _, config in ipairs(JjcGodWarExcel.godWarBoard) do
        for rank = config.rankMin, config.rankMax do
 			local roleData = JjcGodWarDB.getGodWarDataByRank(rank)
			if roleData and not JjcDB.isNpc(roleData) then
				local content = Util.format(mailConfig.content, rank)
           		MailManager.add(MailManager.SYSTEM, roleData.uuid, title, content, config.reward, senderName)

           		--历练系统回调
	            HeroGrowUp.onCallbackByUuid(roleData.uuid, HeroGrowUp.TASKTYPE14, rank)
           		LiLianLogic.onCallbackByUuid(roleData.uuid,LiLianLogic.LILIAN_OUTID2,1,rank)
			end
 		end
    end

    local defConf = JjcGodWarExcel.define[1]
    local mailConfig = MailExcel.mail[MailDefine.MAIL_ID_ZSZZ_GUESS]
    local title = mailConfig.title
    local senderName = mailConfig.senderName    
	local uuid2Yazhu = godWarDB.uuid2Yazhu
	if not uuid2Yazhu then return end
	for uuid,data in pairs(uuid2Yazhu) do
		local cnt = data.jingCaiBi or 0
		if cnt > 0 then
			if cnt > GODWAR_END_JINGCAI then
				cnt = GODWAR_END_JINGCAI
			end
			uuid2Yazhu[uuid].jingCaiBi = 0
			local reward = {}
			reward[1] = {defConf.jingcaibiEnd,cnt}
			MailManager.add(MailManager.SYSTEM, uuid, title, mailConfig.content, reward, senderName)

			--历练系统回调
			local correctCnt = getYaCorrectCnt(data) --本次活动竞猜正确次数
			LiLianLogic.onCallbackByUuid(uuid,LiLianLogic.LILIAN_OUTID25,correctCnt)
		end
	end

	local rank2Uuid = JjcGodWarDB.getGodWarRank2Uuid()
	for rank,uuid in pairs(rank2Uuid) do
		local target = ObjHuman.onlineUuid[uuid]
		if target and target.fd then
			makeTopRank(target,rank)
		else
			local fakeDB = RoleDBLogic.getDb(uuid)
			if fakeDB then
				local fakeHuman = {}
				fakeHuman.db = fakeDB
				makeTopRank(fakeHuman,rank,true)
			end
		end	
	end

	for _, human in pairs(ObjHuman.onlineUuid) do
		if human.fd then
			GC_JJCGODWAR_FINISH(human)
		end
	end
end

local function godwarChengHao(godWarDB)
	local lastTopThree = godWarDB.lastTopThree
	if lastTopThree then
		for rank,roleData in pairs(lastTopThree) do
			if roleData.chenghao then
				RoleHeadLogic.unActive(roleData.uuid, RoleHeadLogic.HEAD_TYPE_4, roleData.chenghao)
			end
		end
	end

	local conf = JjcGodWarExcel.chenghaoReward
	for rank=1,3 do
		local chenghao = conf[rank].chenghaoID
		local uuid = godWarDB.rank2Uuid[rank]
		local roleData = godWarDB.uuid2Roles[uuid]
		if roleData and not JjcDB.isNpc(roleData) then
			godWarDB.uuid2Roles[uuid].chenghao = chenghao --仅作记录，防止称号id配置更换

			-- 给予称号
			local target = ObjHuman.onlineUuid[uuid]
			if target and target.fd then
				RoleHeadLogic.active(target, RoleHeadLogic.HEAD_TYPE_4, chenghao)
			else
				local fakeDB = RoleDBLogic.getDb(uuid)
				if fakeDB then
					local fakeHuman = {}
					fakeHuman.db = fakeDB
					RoleHeadLogic.active(fakeHuman, RoleHeadLogic.HEAD_TYPE_4, chenghao)
					ObjHuman.save(fakeHuman)
				end
			end	
		end
	end
end

function CG_JJCGODWAR_NOWSTATE(human)
	local msgRet = Msg.gc.GC_JJCGODWAR_NOWSTATE
	makeGodWarNowState(msgRet.state)
	--Msg.trace(msgRet)
	Msg.send(msgRet,human.fd)
end

JINGCAI_SHOW_TIP_HAD = JINGCAI_SHOW_TIP_HAD or nil
function jingCaiShowTips(state)
	local need = nil
	for uuid, human in pairs(ObjHuman.onlineUuid) do
		if human.fd and RoleSystemLogic.isOpen(human, RoleSystemDefine.ROLE_SYS_ID_1302) then
			if not JINGCAI_SHOW_TIP_HAD or not JINGCAI_SHOW_TIP_HAD[uuid] then
				need = need or {}
				local index = #need
				need[index+1] = uuid
				
				if index == 10 then
					break
				end
			end
		end
	end

	if need then
		for i=1,#need do
			local uuid = need[i]
			JINGCAI_SHOW_TIP_HAD = JINGCAI_SHOW_TIP_HAD or {}
			JINGCAI_SHOW_TIP_HAD[uuid] = 1
			
			local human = ObjHuman.onlineUuid[uuid]
			local jjcGodWarData = human.db.jjcGodWar
			local jingCaiTip = jjcGodWarData and jjcGodWarData.jingCaiTip or 0
			if not jjcGodWarData or jingCaiTip == 0 then
				human.db.jjcGodWar = human.db.jjcGodWar or {}
				human.db.jjcGodWar.jingCaiTip = state
				GC_JJCGODWAR_JINGCAI_TIP(human)
			end			
		end
	end
end

local function pointCheck(state)
	local godWarDB = JjcGodWarDB.getGodWarDB()
	local uuid2Roles = godWarDB.uuid2Roles
	local pointCheckState = godWarDB.pointCheckState
	if pointCheckState and pointCheckState == state then return end

	godWarDB.pointCheckState = state
	for uuid in pairs(uuid2Roles) do
		local combatResultList = JjcGodWarDB.getCombatResultListByUuid(uuid)
		local point = combatResultList and combatResultList[state] or 0
		if point ~= 0 then
			uuid2Roles[uuid].point = uuid2Roles[uuid].point + point
		end
	end

	JjcGodWarDB.updateGodWarDB(godWarDB)
end

--活动时间控制
--每一轮战斗需要1场竞猜队伍
--每一轮战斗结束后需要刷新排行榜
--每一轮战斗结束后需要结算竞猜结果，给奖励并弹提示
--每一轮准备阶段结束需要保存当前的队伍信息
--战斗阶段最后3s，已无战斗计算队伍，选拔赛6轮内按积分排位，排位赛按小组输赢晋级或止步，仅本轮止步者按原始积分排位
--战斗阶段最后3s，弹竞猜结果提示
function onTimer()
	local godWarDB = JjcGodWarDB.getGodWarDB()
	local state,round,leftTime = getNowGodWarState()
	--print("state,round,leftTime",state,round,leftTime)
	if not state then return end

	if state == GODWAR_STATE_WAIT or state == GODWAR_STATE_END then
		if godWarDB and godWarDB.time and godWarDB.time < os.time() and not godWarDB.isSendReward then
			--结算决赛竞猜
			GC_JJCGODWAR_JINGCAI_WIN(GODWAR_STATE_PAIWEI1,godWarDB)

			--发送活动结束奖励
			godWarDB.isSendReward = true
			sendFinalReward(godWarDB)

			--称号更替
			godwarChengHao(godWarDB)

			JjcGodWarDB.updateGodWarDB(godWarDB)

		--	jjcGodWarIcon()
			jingCaiShowTips(state)		
		end
		return
	end

	--活动开始初始化
	if not godWarDB.time or not Util.isSameDay(godWarDB.time) then
		--print("initGodWar")
		godWarDB = JjcGodWarDB.initGodWar()

	--	jjcGodWarIcon()
		--在线玩家竞猜提醒
		jingCaiShowTips(state)		
	end

	--容错操作 保证每个阶段必然有分组队伍
	JjcGodWarDB.checkMatch(state)

	--生成竞猜队伍
	JjcGodWarDB.godWarJingCaiPairs()

	--准备阶段结算上一阶段竞猜
	if round == GODWAR_JIEDUAN_ZHUNBEI then
		GC_JJCGODWAR_JINGCAI_WIN(state-1,godWarDB) --竞猜成功提示
	end

	--保存队伍信息
	if round == GODWAR_JIEDUAN_JINGCAI then
		--在线玩家竞猜提醒
		jingCaiShowTips(state)
		--保存队伍信息
		JjcGodWarDB.saveCombatData(godWarDB,state)
		--开始战斗
		JjcGodWarCombat.timerCombat() 
	end

	if round == GODWAR_JIEDUAN_COMBAT then
		if JINGCAI_SHOW_TIP_HAD then
			JINGCAI_SHOW_TIP_HAD = nil
		end

		--开始战斗   防止在 竞猜阶段 没有打完
		JjcGodWarCombat.timerCombat() 
		
		if leftTime < 3 then
			if state <= GODWAR_STATE_XUANBA6 then
				--结算本场战斗的积分
				pointCheck(state)
				--选拔赛按积分排位
				JjcGodWarDB.sortJifenBoard() 
			end

			if state >= GODWAR_STATE_XUANBA6 then
				if state >= GODWAR_STATE_PAIWEI32 then 
					--保存战报
					if state >= GODWAR_STATE_PAIWEI16 then
						JjcGodWarDB.makeZhanBao(state)
					end
					--print("sortPaiWeiBoard")
					--排位赛胜者按积分排位，输者淘汰并按积分排位
					JjcGodWarDB.sortPaiWeiBoard(state)
				end
				--print("paiweiFenzu")
				--排位赛完成对手匹配
				JjcGodWarDB.paiweiFenzu(state + 1) 
			end
		end
	end
end

--播放录像
function CG_JJCGODWAR_REPLAY(human,vestID)
	local data = JjcGodWarDB.getRecord(vestID)
	if not data then return end

	CombatLogic.repeatCombat(human,data.combatInfo)
end

--查看两队伍布阵信息
function CG_JJCGODWAR_TEAM(human,vestID)
	local record = JjcGodWarDB.getRecord(vestID)
	if not record then return end

	local msgRet = Msg.gc.GC_JJCGODWAR_TEAM
	msgRet.teams[0] = 2
	local combatInfo = record.combatInfo
	makeGodWarTeamHistory(msgRet.teams[1],combatInfo,CombatDefine.ATTACK_SIDE)
	makeGodWarTeamHistory(msgRet.teams[2],combatInfo,CombatDefine.DEFEND_SIDE)
--	Msg.trace(msgRet)
	Msg.send(msgRet,human.fd)
end

--记录
function CG_JJCGODWAR_RECORD(human)
	local checkState,round,leftTime = getNowGodWarState()
	local msgRet = Msg.gc.GC_JJCGODWAR_RECORD
	msgRet.record[0] = 0

	local allMatch = JjcGodWarDB.getAllMatchByUuid(human.db._id)
	if allMatch then
		local combatResultList = JjcGodWarDB.getCombatResultListByUuid(human.db._id)
		for i=1,#allMatch do
			local matchData = allMatch[i]
			local atkUuid = matchData.atkUuid
			local defUuid = matchData.defUuid
			local state = matchData.state
			local winUuid = matchData.winUuid
			local vestID = matchData.vestID
			local point = combatResultList and combatResultList[state] or 0
			
			local canSend = true
			if winUuid == "" then
				canSend = nil
			end 
			if state == checkState and round ~= GODWAR_JIEDUAN_COMBAT then
				canSend = nil
			end

			if state == checkState and round == GODWAR_JIEDUAN_COMBAT and leftTime > 1 then
				canSend = nil
			end

			if canSend then
				msgRet.record[0] = msgRet.record[0] + 1
				local index = msgRet.record[0]
				msgRet.record[index].roles[0] = 2
				local atkRoleData = JjcGodWarDB.getGodWarDataByUuid(atkUuid)
				local defRoleData = JjcGodWarDB.getGodWarDataByUuid(defUuid)
				local atkRolebase = atkRoleData.rolebase
				local defRolebase = defRoleData.rolebase
				if JjcDB.isNpc(atkRoleData) then
					atkRolebase = atkRoleData
				end
				if JjcDB.isNpc(defRoleData) then
					defRolebase = defRoleData
				end

				RoleLogic.makeRoleBase(atkRolebase,msgRet.record[index].roles[1])
				RoleLogic.makeRoleBase(defRolebase,msgRet.record[index].roles[2])

				msgRet.record[index].winUuid = winUuid
				msgRet.record[index].vestID = vestID
				msgRet.record[index].state = state
				msgRet.record[index].point = point
			end
		end
	end

	--Msg.trace(msgRet)
	Msg.send(msgRet,human.fd)
end

--战报
function CG_JJCGODWAR_ZHANBAO(human,vestID)
	if vestID == "" then return end

	local record = JjcGodWarDB.getRecord(vestID)
	if not record then return end

	local combatInfo = record.combatInfo
	if not combatInfo then return end

	local msgRet = Msg.gc.GC_JJCGODWAR_ZHANBAO
	msgRet.win = combatInfo.isWin and 1 or 2
	msgRet.roles[0] = 2
	msgRet.result[0] = 0
	RoleLogic.makeRoleBase(combatInfo.attacker, msgRet.roles[2])
	RoleLogic.makeRoleBase(combatInfo.defender, msgRet.roles[1])
	for pos = 1, CombatDefine.COMBAT_HERO_ALL_CNT do
		local obj = combatInfo.objList and combatInfo.objList[pos]
		if obj then
			msgRet.result[0] = msgRet.result[0] + 1
			local index = msgRet.result[0]
			CombatLogic.fontFinishResultNet(msgRet.result[index], obj)
		end 
	end
	msgRet.vestID = vestID
	--Msg.trace(msgRet)
	Msg.send(msgRet,human.fd)
end

function jjcGodWarFinishGm(human)
	local state,round,leftTime = getNowGodWarState()
	if state > GODWAR_STATE_WAIT and state < GODWAR_STATE_END then return end

	local db = JjcGodWarDB.getGodWarDB()
	if not db or not db.time then return end
	local msgRet = Msg.gc.GC_JJCGODWAR_FINISH
	msgRet.actTime = db.time
	msgRet.roleBase[0] = 0
	local rank2Uuid = JjcGodWarDB.getGodWarRank2Uuid()
	local uuid2Roles = JjcGodWarDB.getGodWarUuid2Roles()
	if not rank2Uuid or not uuid2Roles then return end

	local conf = JjcGodWarExcel.chenghaoReward
	msgRet.roleBase[0] = 3
	for i=1,3 do
		local uuid = rank2Uuid[i]
		local roleData = uuid2Roles[uuid]
		local rolebase = roleData.rolebase
		if JjcDB.isNpc(roleData) then
			rolebase = roleData
		end
		RoleLogic.makeRoleBase(rolebase, msgRet.roleBase[i])
		msgRet.roleBase[i].chenghao = conf[i].chenghaoID
	end

	--Msg.trace(msgRet)
	Msg.send(msgRet,human.fd)
end

--活动结算弹窗
function GC_JJCGODWAR_FINISH(human)
	if not RoleSystemLogic.isOpen(human, RoleSystemDefine.ROLE_SYS_ID_1302) then
		return
	end

	local state,round,leftTime = getNowGodWarState()
	if state > GODWAR_STATE_WAIT and state < GODWAR_STATE_END then return end

	local db = JjcGodWarDB.getGodWarDB()
	if not db or not db.time then return end

	if human.db.jjcGodWar then
		local finishTipTime = human.db.jjcGodWar.finishTipTime
		if finishTipTime then
			if Util.isSameDayByTimes(finishTipTime,db.time) then return end
		end
	end

	local msgRet = Msg.gc.GC_JJCGODWAR_FINISH
	msgRet.actTime = db.time
	msgRet.roleBase[0] = 0
	local rank2Uuid = JjcGodWarDB.getGodWarRank2Uuid()
	local uuid2Roles = JjcGodWarDB.getGodWarUuid2Roles()
	if not rank2Uuid or #rank2Uuid <= 0 or not uuid2Roles or uuid2Roles == {} then return end

	local conf = JjcGodWarExcel.chenghaoReward
	msgRet.roleBase[0] = 3
	for i=1,3 do
		local uuid = rank2Uuid[i]
		local roleData = uuid2Roles[uuid]
		local rolebase = roleData.rolebase
		if JjcDB.isNpc(roleData) then
			rolebase = roleData
		end
		RoleLogic.makeRoleBase(rolebase, msgRet.roleBase[i])
		msgRet.roleBase[i].chenghao = conf[i].chenghaoID
	end

	human.db.jjcGodWar = human.db.jjcGodWar or {}
	human.db.jjcGodWar.finishTipTime = db.time

	--Msg.trace(msgRet)
	Msg.send(msgRet,human.fd)
end

function onLogin(human)
	GC_JJCGODWAR_FINISH(human)
end

function updateDaily(human)
	if not human.db.jjcGodWar then return end
	human.db.jjcGodWar.mobaiList = nil
	human.db.jjcGodWar.mobaiCnt = nil
	human.db.jjcGodWar.jingCaiTip = nil
end

--------------------------------- JjcActLogic回调 -------------------------------

local function getActNearTime()
	local startTime1,startTime2 = getStartTime()
    if not startTime1 then 
    	return JjcActLogic.STATE_NOOPEN, 0, 0
    end

	local now = os.time()
	local endTime1 = startTime1 + GODWAR_ACT_TIME
	local endTime2 = startTime2 + GODWAR_ACT_TIME
	if startTime1 <= now and now < endTime1 then
		return JjcActLogic.STATE_START, startTime1, endTime1 - now
	end
	if startTime2 <= now and now < endTime2 then
		return JjcActLogic.STATE_START, startTime2, endTime2 - now
	end	
	if now < startTime1 then
		return JjcActLogic.STATE_READY, startTime1, startTime1 - now
	end
	if now < startTime2 then
		return JjcActLogic.STATE_READY, startTime2, startTime2 - now
	end

	startTime1 = startTime1 + 86400 * 7
	return JjcActLogic.STATE_NORMAL, startTime1, startTime1 - now 
end

-- 活动状态 进行中/准备 剩余时间
function getActState(human)
	local state, _, leftTime = getActNearTime()
	--print("state, leftTime",state, leftTime)
	return state, leftTime
end

function getActDesc(desc)
	local _, startTime = getActNearTime()
	local now = os.time()
	if Util.isSameDay(startTime, now) or startTime == 0  then
		local d = os.date("*t", startTime)
		return Util.format(desc, d.month .. "." .. d.day)
	else
		local startTime1,startTime2 = getStartTime()
		local realTime = 0
		if  now < startTime1 then
			realTime = startTime1
		elseif now < startTime2 then
			realTime = startTime2
		elseif now > startTime2 then
			realTime = startTime2
		end
		local d = os.date("*t", realTime)
		return Util.format(desc, d.month .. "月" .. d.day) 
	end
	
end

function fontActArgs(args, human)
    args[0] = 1
    args[1] = getMyTopRank(human)
end


function getLeftTime(human, YYInfo, funcConfig)
	local state, startTime, leftTime = getActNearTime()
	if state == JjcActLogic.STATE_READY and leftTime <= 75900 then
		return leftTime
	end
end

function isOpen(human)
	local state, startTime, leftTime = getActNearTime()
	if state == JjcActLogic.STATE_NOOPEN then return end
	if state == JjcActLogic.STATE_READY and leftTime > 75900 then return end

	return true
end

function getYunYingState(human, YYInfo, funcConfig)
	local state,round = getNowGodWarState()
	if state == GODWAR_STATE_WAIT or state == GODWAR_STATE_END then return end

	return YunYingLogic.STATE_STARTING
end

function jjcGodWarIcon()
	local msgRet = Msg.gc.GC_JJCGODWAR_ICON
	makeGodWarNowState(msgRet.state)	

	for k , v in ipairs(JjcGodWarExcel.godWarBoard[1].reward) do
		Grid.makeItem(msgRet.items[k],  v[1], v[2])
		msgRet.items[0] = k
	end

	for _, human in pairs(ObjHuman.onlineUuid) do
		if human.fd then
			Msg.send(msgRet,human.fd)
		end
	end
end

function checkCanPos(human)
	local state,round = getNowGodWarState()
	if state == GODWAR_STATE_WAIT or state == GODWAR_STATE_END then return true end

	if round ~= GODWAR_JIEDUAN_ZHUNBEI then
		return Broadcast.sendErr(human,Lang.GODWAR_POS_ERR)
	end

	return true
end

function queryGm(human, value)
	print("  queryGm ", value)
	local msgRet = Msg.gc.GC_JJCGODWAR_DANMU_QUERY
	msgRet.cnt = 0
	for i=1,value do
		local net = msgRet.list[i]
		net.uuid = "21312412412"
		net.desc = "芜湖 芜湖 芜湖 芜湖"
	end
	msgRet.list[0] = value
	Msg.send(msgRet,human.fd)
end

-- 弹幕
function danmuQuery(human)

	local list = JjcGodWarDB.getGodWarDanMuList()
	list = list or {}
	local msgRet = Msg.gc.GC_JJCGODWAR_DANMU_QUERY
	for k, v in ipairs(list) do
		local net = msgRet.list[k]
		net.uuid = v.uuid
		net.desc = v.desc
	end
	msgRet.list[0] = #list
	Grid.makeItem(msgRet.need,  ItemDefine.ITEM_JINBI_ID, 1000)
	Msg.send(msgRet,human.fd)
end

function danmuSpeak(human, desc)
	local state,round = getNowGodWarState()
--	if state == GODWAR_STATE_WAIT or state >= GODWAR_STATE_END then return end

	if BagLogic.getItemCnt(human, ItemDefine.ITEM_JINBI_ID) < 1000 then
		return Broadcast.sendErr(human, Util.format(Lang.COMMON_NO_ITEM, ItemDefine.getValue(ItemDefine.ITEM_JINBI_ID, "name"))) 
	end
	
	BagLogic.delItem(human, ItemDefine.ITEM_JINBI_ID, 1000, "jjc_godwar")

	desc = FilterUtil.filter(desc)
	JjcGodWarDB.updateDanMu(human.db._id, desc)
	local msgRet = Msg.gc.GC_JJCGODWAR_DANMU_SPEAK
	msgRet.uuid = human.db._id
	msgRet.desc = desc

	for _, fakeHuman in pairs(ObjHuman.onlineUuid) do
		Msg.send(msgRet,fakeHuman.fd)
	end
	
end
